import { Http } from '../../lib/http/index';
// import Auth from '../auth/index';
import UserLogin from '../login';
import urlMap from './urlMap';

function isString (o) {
  // 是否字符串
  return Object.prototype.toString.call(o).slice(8, -1) === 'String';
}

class MyHttp extends Http {
  constructor () {
    super();
    this.init();
    this.urlMap = urlMap;
    this.instance = null;
  }

  static getInstance () {
    if (!this.instance) {
      this.instance = new MyHttp();
    }
    return this.instance;
  }
  init () {
    this.interceptor = {
      before: _config => {
        // 获取权限 permission
    /*    if (_config.permission) {
          let permissions = _config.permission.toString().split(',');
          let _hasPermission = true;
          for (let i = 0, leng = permissions.length; i < leng; i++) {
            if (!Auth.checkPermission(permissions[i])) {
              _hasPermission = false;
              break;
            }
          }
          // 如果该用户没有检测的权限，不继续执行
          if (!_hasPermission) {
            return false;
          }
        }*/
        // 该请求是否需要登录
        if (_config.needLogin) {
          if (!UserLogin.checkIfLogin()) {
            return false;
          }
          let _token = UserLogin.getToken();
          if (_token) {
            _config['header']['token'] = _token;
            _config.url = this.addToken(_config.url, _token);
          } else {
            return false;
          }
        }

        return _config;
      },
      after: res => {
        // TODO 处理如果返回未登录的情况
        let statusCode = res.statusCode;
        if (statusCode === 401) {
          UserLogin.logout();
          UserLogin.showLoginTips();
        }

        if (res.data && res.data.code === 0) {
          if (isString(res.data.msg)) {
            uni.showToast({
              icon: 'none',
              title: (res.data.msg && res.data.msg.toString()),
              duration: 3000
            });
          } else {
            uni.showToast({
              icon: 'none',
              title: '错误'
            });
          }
        }
        return res;
      }
    };
  }
  // 通用的post请求
  post (params) {
    return super.post(params);
  }
  // 通用的get请求
  get (params) {
    return super.get(params);
  }
  addToken (url, token) {
    if (url.indexOf('?') === -1) {
      url = `${url}?token=${token}`;
    } else {
      url = url.replace('?',
        `?token=${token}&`);
    }
    return url;
  }
}

let _myHttp = MyHttp.getInstance();
export default _myHttp;
